package com.abo.yaas.view.widgets.panels;

import com.abo.yaas.authentication.SessionHandler;
import com.abo.yaas.domain.Auction;
import com.abo.yaas.domain.AuctionState;
import com.abo.yaas.i18n.Lang;
import com.abo.yaas.i18n.LocaleChangeListener;
import com.abo.yaas.i18n.LocaleChangedEvent;
import com.abo.yaas.view.AbstractView;
import com.abo.yaas.view.widgets.forms.AuctionForm;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class AuctionFormPanel extends AbstractView<VerticalLayout> implements
        LocaleChangeListener {
    private final AuctionForm form = new AuctionForm();

    private final VerticalLayout layout;

    private final Panel panel;

    public AuctionFormPanel() {
        super(new VerticalLayout());
        layout = getContent();
        layout.setSizeUndefined();
        layout.setWidth("100%");
        layout.setMargin(true);
        panel = new Panel();
        panel.setCaption("Create Auction");
        panel.setWidth("450px");
        final VerticalLayout panelLayout = (VerticalLayout) panel.getContent();
        panelLayout.setMargin(true);
        panel.addComponent(form);
        layout.addComponent(panel);
        layout.setComponentAlignment(panel, Alignment.MIDDLE_CENTER);
        Lang.addListener(this);
    }

    @Override
    public void activated(Object... params) {
        boolean readonly = false;
        Auction auction = null;
        for (final Object param : params) {
            if (param instanceof Auction) {
                readonly = true;
                auction = (Auction) param;
            }
        }
        if (auction == null) {
            auction = new Auction();
            auction.setOwner(SessionHandler.getUser());
            auction.setState(AuctionState.AS_ACTIVE);
        }
        form.setItemDataSource(new BeanItem<Auction>(auction));
        form.setReadOnly(readonly);
    }

    @Override
    public void deactivated(Object... params) {/* NOP */
    }

    @Override
    public void localeChanged(LocaleChangedEvent event) {
        panel.setCaption(Lang.getMessage("CREATE_AUCTION_PANEL"));
        if (form.getItemDataSource() != null) {
            form.setItemDataSource(form.getItemDataSource());
        }
    }

}
